//
//  UIControl+LMRepeat.m
//  WelfareManager
//
//  Created by longmin on 17/3/9.
//  Copyright © 2017年 timtian. All rights reserved.
//

#import "UIControl+LMRepeat.h"
#import <objc/runtime.h>

@interface UIControl()

@property(nonatomic, assign) BOOL lm_ignoreEvent;

@end

@implementation UIControl (LMRepeat)

+ (void)load
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
       
        SEL selA = @selector(sendAction:to:forEvent:);
        
        SEL selB = @selector(lm_sendAction:to:forEvent:);
        
        Method methodA =class_getInstanceMethod(self, selA);
        
        Method methodB =class_getInstanceMethod(self, selB);
        
        BOOL isAdd = class_addMethod(self, selA,method_getImplementation(methodB),method_getTypeEncoding(methodB));
        
        if(isAdd) {
            
            class_replaceMethod(self, selB,method_getImplementation(methodA),method_getTypeEncoding(methodA));
            
        }else{
            
            method_exchangeImplementations(methodA, methodB);
            
        }
        
    });
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        self.lm_repeatInterval = 1.0;
//        self.lm_ignoreEvent = NO;
    }
    return self;
}
static const char *LM_RepeatInterval = "lm_repeatInterval";
static const char *LM_IgnoreEvent = "lm_ignoreEvent";
- (void)setLm_repeatInterval:(double)lm_repeatInterval {
    
    objc_setAssociatedObject(self,
                             LM_RepeatInterval,
                             @(lm_repeatInterval),
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (double)lm_repeatInterval {
    return [objc_getAssociatedObject(self, LM_RepeatInterval) doubleValue];
}

- (void)setLm_ignoreEvent:(BOOL)lm_ignoreEvent {
    objc_setAssociatedObject(self,
                             LM_IgnoreEvent,
                             @(lm_ignoreEvent),
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)lm_ignoreEvent {
    return [objc_getAssociatedObject(self, LM_IgnoreEvent) doubleValue];
}

- (void)lm_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    
    if (self.lm_ignoreEvent) return;

    if (self.lm_repeatInterval > 0) {
        self.lm_ignoreEvent = YES;
        [self performSelector:@selector(setLm_ignoreEvent:) withObject:@(NO) afterDelay:self.lm_repeatInterval];

    }
    
    [self lm_sendAction:action to:target forEvent:event];
}

@end
